import { lazy, useEffect } from "react"
import { createBrowserRouter, RouterProvider, Navigate, RouteObject } from "react-router-dom"
import RouterErrorElement from "./router-error"
import { App } from "antd"
import { antdUtils } from "@/utils/message"

export const basicRouter = createBrowserRouter([
  {
    path: "/login",
    Component: lazy(() => import("@/components/login"))
  },
  {
    path: "/",
    element: <Navigate to="/dashboard/main" />
  },
  {
    path: "*",
    Component: lazy(() => import("@/layout")),
    children: [],
    errorElement: <RouterErrorElement />
  }
])

export const toLoginPage = () => {
  basicRouter.navigate("/login")
}

function findNodeByPath(routes: RouteObject[], path: string) {
  for (let i = 0; i < routes.length; i += 1) {
    const element = routes[i]
    if (element.path === path) return element
    findNodeByPath(element.children || [], path)
  }
}

export const addRoutes = (parentPath: string, routes: RouteObject[]) => {
  if (!parentPath) {
    basicRouter.routes.push(...(routes as any))
    return
  }

  const curNode = findNodeByPath(basicRouter.routes, parentPath)

  if (curNode?.children) {
    curNode?.children.push(...routes)
  } else if (curNode) {
    curNode.children = routes
  }
}

export const replaceRoutes = (parentPath: string, routes: RouteObject[]) => {
  if (!parentPath) {
    basicRouter.routes.push(...(routes as any))
    return
  }

  const curNode = findNodeByPath(basicRouter.routes, parentPath)

  if (curNode) {
    curNode.children = routes
  }
}

const Router = () => {
  const { notification, message, modal } = App.useApp()

  useEffect(() => {
    antdUtils.setMessageInstance(message)
    antdUtils.setNotificationInstance(notification)
    antdUtils.setModalInstance(modal)
  }, [notification, message, modal])

  return <RouterProvider router={basicRouter} />
}

export default Router
